#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define N 64

int main(int argc, char const *argv[])
{
    //创建socket
    int broadfd;

    //创建一个socket文件描述符
    broadfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(broadfd < 0)
    {
        perror("sock err");
        return -1;
    }

//打开广播设置，允许发送广播包
#if 1  
    int on = 1;
    if(setsockopt(broadfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0)
    {
        perror("set err");
        return -1;
    }
#endif

    ssize_t len;
    char buf[N] = {0};
    struct sockaddr_in broad_addr;

    broad_addr.sin_family = AF_INET;
    broad_addr.sin_port = htons(8888);  //端口号  
    broad_addr.sin_addr.s_addr = inet_addr("192.168.51.255");  //IP

    int addrlen = sizeof(broad_addr);

    //发送"coffee"代表公司名
    int ret = sendto(broadfd, "message", 7, 0, (struct sockaddr *)&broad_addr, addrlen);
    if(ret < 0)
    {
        perror("send to err");
        return -1;
    }

    //如果对方回复"yes"，那么接收对方的地址
    struct sockaddr_in dev_addr;
    recvfrom(broadfd, buf, N, 0, (struct sockaddr *)&dev_addr, &addrlen);
    if(strcmp(buf, "yes") != 0)
    {
        printf("not my company device\n");
        return -1;
    }
    printf("ip: %s, port: %d, data: %s\n", inet_ntoa(dev_addr.sin_addr),
         ntohs(dev_addr.sin_port), buf);
    //建立TCP连接
    int tcpfd = socket(AF_INET, SOCK_STREAM, 0);
    if(tcpfd < 0)
    {
        perror("sock err");
        return -1;
    }

    if(connect(tcpfd, (struct sockaddr *)&dev_addr, addrlen) < 0)
    {
        perror("connect err");
        return -1;
    }

    printf("connect success\n");

    close(broadfd);
    close(tcpfd);

    return 0;
}
